/*
 * @Author: lyuan2018
 * @Date: 2019-08-08 11:01:16
 * @Last Modified by: lyuan2018
 * @Last Modified time: 2020-09-10 10:58:47
 * 邮件设置--账户管理--编辑账户页面
 */
import React, { Component } from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { Button, Spin, Modal, message } from 'antd';
import {
  WeaLocaleProvider,
  WeaDialog,
  WeaSearchGroup,
  WeaMoreButton,
  WeaHelpfulTip,
  WeaTagGroup,
  WeaError,
} from 'ecCom';
import { RenderForm } from '../util';
import { ResultPage } from './Result';
import { ExchangeResult } from './ExchangeResult';
import RenderChooseFolder from './RenderChooseFolderDialog';

const getLabel = WeaLocaleProvider.getLabel;

@inject('settingStore')
@observer
class Edit extends Component {
  constructor(props) {
    super(props);
    this.prefixCls = `${props.class}-edit`;
    this.state = {
      autoGetFolderVisible: false,
      chooseFolders: [],
      autoGetFolderLoading: false,
      chooseFolderName: '',
    };
  }

  componentWillUnmount() {
    const {
      settingStore: { accountStore },
    } = this.props;
    accountStore.clear();
  }

  formChange = (data, change) => {
    // function just use in this page
    const {
      settingStore: { accountStore },
    } = this.props;
    const { fields, accountForm } = accountStore;
    let newfields = fields;
    let option = Object.getOwnPropertyNames(data)[0];
    if (Object.prototype.hasOwnProperty.call(data, option)) {
      let value = data[option].value;
      let temp = fields[1].items.find(item => item.domkey[0] === change); // if repeat use, please change the fields index to your need
      if (value === '0') {
        temp.viewAttr = 2;
        newfields[1].items = newfields[1].items.map((field) => {
          if (field.domkey[0] === change) {
            field = {
              ...field,
              viewAttr: '2',
              otherParams: { disabled: false, hideLabel: true },
            };
          }
          return field;
        });
        accountStore.setStoreState({ fields: newfields });
        option === 'sendneedSSL' &&
          accountForm.updateFields({ smtpServerPort: { value: '25' } });
      } else if (value === '1') {
        temp.viewAttr = 1;
        newfields[1].items = newfields[1].items.map((field) => {
          if (field.domkey[0] === change) {
            field = {
              ...field,
              viewAttr: '1',
              otherParams: { disabled: true, hideLabel: true },
            };
          }
          return field;
        });
        accountStore.setStoreState({ fields: newfields });
        option === 'sendneedSSL' &&
          accountForm.updateFields({ smtpServerPort: { value: '465' } });
      }
    }
  };

  serverTypeChange = (data, form) => {
    let type = data.serverType.value;
    let getneedSSL = form.getFormParams().getneedSSL;
    if (type === '1') {
      form.updateFields({
        popServerPort: getneedSSL === '1' ? '995' : '110',
        popServer: '',
      });
    } else if (type === '2') {
      form.updateFields({
        popServerPort: getneedSSL === '1' ? '993' : '143',
        popServer: '',
      });
    }
  };

  getneedSSLChange = (data, form) => {
    let getneedSSL = data.getneedSSL.value;
    let serverType = form.getFormParams().serverType;
    if (serverType === '2') {
      form.updateFields({ popServerPort: getneedSSL === '1' ? '993' : '143' });
    } else {
      form.updateFields({ popServerPort: getneedSSL === '1' ? '995' : '110' });
    }
  };

  openIdentifyInvoiceChange = (data) => {
    let type = data.openIdentifyInvoice.value;
    if (type === '1') {
      Modal.info({
        title: getLabel(510826, '温馨提示'),
        content: (
          <div className="wea-list-confirm">
            <p style={{ 'font-weight': '700' }}>
              {getLabel(515692, '亲爱的用户，欢迎使用发票识别功能。')}
            </p>
            <p>
              {getLabel(
                515695,
                '1.为保证发票识别功能正常使用，我们会根据需要收集个人邮箱中公司指定发件人发送的发票信息，获取之后也仅作为用户及其公司在OA系统中的相关财务业务往来',
              )}
            </p>
            <p>
              {getLabel(
                515696,
                '2.我们非常重视您的隐私和个人信息保护，未经授权，不会私自收集、使用、共享您邮件中的个人信息，请放心使用',
              )}
            </p>
          </div>
        ),
        okText: getLabel(826, '确定'),
        onOk: () => {},
      });
    }
  };

  onSentItemsChange = (data) => {
    const {
      settingStore: { accountStore },
    } = this.props;
    const { accountForm } = accountStore;
    const sentItemsValue = data.length > 1 ? [data[data.length - 1]] : data;
    accountForm.updateFields({
      sentItems: { value: toJS(sentItemsValue) },
    });
  };

  getForm = (form, fields) => {
    const { isFormInit } = form;
    const {
      serverType,
      needSave,
      isReceiveSent,
      sentItems,
    } = form.getFormParams();
    let group = [];
    isFormInit &&
      fields &&
      fields.map((c, index) => {
        let items = [];
        if (index === 0) {
          c.items.map((field) => {
            if (field.domkey[0] === 'openIdentifyInvoice') {
              // 开启发票识别
              items.push({
                com: RenderForm(form, field, { style: { width: '100%' } }, '', {
                  onChange: data =>
                    this.openIdentifyInvoiceChange(data, form),
                }),
              });
            } else {
              items.push({ com: RenderForm(form, field) });
            }
          });
          group.push(
            <WeaSearchGroup
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaSearchGroup@4eaupi@${c.title}`}
              col={1}
              title={c.title}
              needTigger={true}
              showGroup={c.defaultshow}
              items={items}
            />,
          );
        } else if (index === 1) {
          group.push(
            <WeaSearchGroup
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaSearchGroup@o406b3@${c.title}`}
              col={1}
              title={c.title}
              needTigger={true}
              showGroup={c.defaultshow}
              className={`${this.prefixCls}-group`}
            >
              {c.items.map((field) => {
                if (field.domkey[0] === 'serverType') {
                  // 邮箱服务器类型
                  return RenderForm(
                    form,
                    field,
                    { style: { width: '54%' } },
                    '',
                    { onChange: data => this.serverTypeChange(data, form) },
                  );
                } else if (
                  field.domkey[0] === 'popServer' ||
                  field.domkey[0] === 'smtpServer'
                ) {
                  if (serverType !== '3') {
                    return RenderForm(form, field, { style: { width: '54%' } });
                  }
                } else if (field.domkey[0] === 'getneedSSL') {
                  if (serverType !== '3') {
                    return RenderForm(
                      form,
                      field,
                      { style: { width: '15%' } },
                      '',
                      { onChange: data => this.getneedSSLChange(data, form) },
                    );
                  }
                } else if (
                  field.domkey[0] === 'popServerPort' ||
                  field.domkey[0] === 'smtpServerPort'
                ) {
                  if (serverType !== '3') {
                    return RenderForm(form, field, { style: { width: '30%' } });
                  }
                } else if (
                  field.domkey[0] === 'ews_service_url' ||
                  field.domkey[0] === 'ews_domain' ||
                  field.domkey[0] === 'ews_version'
                ) {
                  if (serverType === '3') {
                    let newField = {
                      ...toJS(field),
                      fieldcol: 16,
                      labelcol: 7,
                    };
                    return RenderForm(form, newField, {
                      style: { width: '100%' },
                    });
                  }
                } else if (field.domkey[0] === 'sendneedSSL') {
                  if (serverType !== '3') {
                    return RenderForm(
                      form,
                      field,
                      { style: { width: '15%' } },
                      '',
                      {
                        onChange: data => this.formChange(data, 'isStartTls'),
                      },
                    );
                  }
                } else if (field.domkey[0] === 'needSave') {
                  // 保留服务器上的邮件
                  if (serverType !== '3') {
                    let helptip = (
                      <WeaHelpfulTip
                        ecId={`${
                          (this && this.props && this.props.ecId) || ''
                        }_WeaHelpfulTip@ijyeri`}
                        title={getLabel(
                          510163,
                          '关闭后将删除邮箱服务器上的对应邮件，请谨慎设置！',
                        )}
                        placement="right"
                      />
                    );
                    let warningtip = (
                      <span style={{ color: 'red' }}>
                        {getLabel(
                          510163,
                          '关闭后将删除邮箱服务器上的对应邮件，请谨慎设置！',
                        )}
                      </span>
                    );
                    let needSaveSpan = needSave === '1' ? helptip : warningtip;
                    return RenderForm(
                      form,
                      field,
                      { style: { width: '100%' } },
                      needSaveSpan,
                      // {onChange: (data) => this.needSaveChange(data, form)}
                    );
                  }
                } else if (field.domkey[0] === 'isStartTls') {
                  if (serverType !== '3') {
                    return RenderForm(
                      form,
                      field,
                      { hideLabel: true, style: { width: '100%' } },
                      <span>
                        {getLabel(
                          129992,
                          '如果服务器支持，就使用STARTTLS加密传输',
                        )}
                      </span>,
                      {
                        onChange: data =>
                          this.formChange(data, 'sendneedSSL'),
                      },
                    );
                  }
                } else if (field.domkey[0] === 'needCheck') {
                  if (serverType !== '3') {
                    return RenderForm(form, field, {
                      style: { width: '100%' },
                    });
                  }
                } else if (field.domkey[0] === 'isReceiveSent') {
                  if (serverType === '3' || serverType === '2') {
                    return RenderForm(form, field, {
                      style: { width: '100%' },
                    });
                  }
                } else if (field.domkey[0] === 'sentItems') {
                  if (serverType === '2' && isReceiveSent === '1') {
                    return RenderForm(
                      form,
                      field,
                      { style: { width: '100%' } },
                      null,
                      {},
                      [
                        <WeaError
                          ecId={`${
                            (this && this.props && this.props.ecId) || ''
                          }_WeaError@cvxw24@${field.domkey[0]}`}
                          tipPosition="bottom"
                          ref="sentItemsError"
                          error={getLabel('523072', '已发送文件夹名称未填写')}
                        >
                          <WeaTagGroup
                            ecId={`${
                              (this && this.props && this.props.ecId) || ''
                            }_WeaTagGroup@bhh432@${field.domkey[0]}`}
                            datas={Array.isArray(sentItems) ? sentItems : []}
                            type="emailOuterInput"
                            hasOps={false}
                            noSearch
                            onChange={this.onSentItemsChange}
                          />
                        </WeaError>,
                        <div className={`${this.prefixCls}-form-receiveSent`}>
                          <Button
                            ecId={`${
                              (this && this.props && this.props.ecId) || ''
                            }_Button@sd108a@${field.domkey[0]}`}
                            onClick={this.onAutoGetFolderName}
                            loading={this.state.autoGetFolderLoading}
                          >
                            {getLabel('522596', '自动获取')}
                          </Button>
                        </div>,
                      ],
                    );
                  }
                } else if (field.domkey[0] === 'sentLastTime') {
                  if (isReceiveSent === '1') {
                    return RenderForm(form, field, {
                      style: { width: '100%' },
                    });
                  }
                } else {
                  return RenderForm(form, field, { style: { width: '100%' } });
                }
              })}
            </WeaSearchGroup>,
          );
        }
      });
    return group;
  };

  onAutoGetFolderName = () => {
    const {
      settingStore: { accountStore },
    } = this.props;
    const { accountForm, onGetFolderName } = accountStore;
    const {
      popServer,
      accountMailAddress,
      accountPassword,
    } = accountForm.getFormParams();
    if (popServer.trim()) {
      let params = {
        mailuserAddress: accountMailAddress,
        mailuserPassword: accountPassword,
        imapServer: popServer,
      };
      this.setState({ autoGetFolderLoading: true }, async () => {
        let res = await onGetFolderName(params);
        if (res.getFolderStatus === '1') {
          let chooseFolders = res.sentItemNames.map((item, index) => ({
            key: index,
            showname: item.folderName,
            selected: false,
            isRec: item.isRec || false,
          }));
          this.setState({ chooseFolders, autoGetFolderVisible: true });
        } else {
          message.error(getLabel(522602, '获取失败，请重试！'));
        }
        this.setState({ autoGetFolderLoading: false });
      });
    } else {
      Modal.warning({
        content: getLabel('522601', '请填写 接收邮件服务器 信息'),
      });
    }
  };

  onCancelAutoGetFolder = () => this.setState({ autoGetFolderVisible: false });

  onChangeFolderName = (v) => {
    this.setState({ chooseFolderName: v });
  };

  onSetFolderName = () => {
    const {
      settingStore: { accountStore },
    } = this.props;
    const { accountForm } = accountStore;
    const { chooseFolderName, chooseFolders } = this.state;
    if (chooseFolderName.toString()) {
      let folderName = chooseFolders.filter(
        item => item.key === chooseFolderName,
      );
      folderName = folderName && folderName[0];
      folderName = (folderName && folderName.showname) || '';
      if (folderName) {
        accountForm.updateFields({
          sentItems: {
            value: [{ id: folderName, name: folderName, validate: true }],
          },
        });
        this.setState({ autoGetFolderVisible: false, chooseFolderName: '' });
      }
    } else {
      message.warning(getLabel('522597', '您还未选择文件夹！'));
    }
  };

  needSaveChange = (data, form) => {
    let isSave = Object.getOwnPropertyNames(data)[0];
    if (Object.prototype.hasOwnProperty.call(data, isSave)) {
      let value = data[isSave].value;
      if (value * 1 === 0) {
        // 关闭
        Modal.confirm({
          title: getLabel(
            510162,
            '关闭后将删除邮箱服务器上的对应邮件，确定关闭？',
          ),
          okText: getLabel(826, '确定'),
          cancelText: getLabel(201, '取消'),
          onCancel: () => {
            form.updateFields({ needSave: { value: '1' } });
          },
        });
      }
    }
  };

  onEditSubmit = () => {
    const {
      settingStore: { accountStore },
    } = this.props;
    const { editSubmit, accountForm } = accountStore;
    let formParams = accountForm.getFormParams();
    let flag = true;

    if (formParams.serverType === '2' && formParams.isReceiveSent === '1') {
      if (
        !formParams.sentItems ||
        (Array.isArray(formParams.sentItems) &&
          formParams.sentItems.length === 0)
      ) {
        this.refs.sentItemsError.showError();
        flag = false;
      }
    }

    if (flag) {
      editSubmit();
    }
  };

  onCancel = () => {
    const {
      settingStore: { accountStore },
    } = this.props;
    const { setStoreState, accountForm } = accountStore;
    setStoreState({
      editVisible: false,
      editId: '',
      mailType: '',
      editStep: 1,
      fields: [],
    });
    window.e9HideFormFieldKeys = [];
    accountForm.resetForm();
    accountStore.clear();
  };

  toPreviewStep = () => {
    const {
      settingStore: { accountStore },
    } = this.props;
    accountStore.setStoreState({
      editStep: accountStore.editStep - 1,
      editResult: {},
    });
  };

  render() {
    const {
      settingStore: { accountStore },
    } = this.props;
    const {
      editVisible,
      accountForm,
      fields,
      editStep,
      validateLoading,
      editResult,
      editLoading,
      mailType,
    } = accountStore;
    const buttons =
      editStep === 1
        ? [
            <Button
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_Button@ro3gvu@onsave`}
              type="primary"
              onClick={this.onEditSubmit}
            >
              {getLabel(30986, '保存')}
            </Button>,
            <WeaMoreButton
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaMoreButton@v7a9ih@more`}
            />,
          ]
        : [
            (toJS(editResult) == null ||
              (toJS(editResult) != null && !toJS(editResult).mailState)) && (
              <Button
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_Button@w50etw@pre`}
                type="primary"
                onClick={this.toPreviewStep}
              >
                {getLabel(1876, '上一步')}
              </Button>
            ),
            <Button
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_Button@wyb2vo@close`}
              type="primary"
              onClick={this.onCancel}
            >
              {getLabel(309, '关闭')}
            </Button>,
            <WeaMoreButton
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaMoreButton@1skds9@more`}
            />,
          ];
    return (
      <WeaDialog
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaDialog@lpwpuf`}
        icon="icon-coms-email"
        iconBgcolor="#a0b0ba"
        title={getLabel(384440, '编辑账户信息')}
        style={{ width: 714, height: 600 }}
        className={this.prefixCls}
        visible={editVisible}
        onCancel={this.onCancel}
        buttons={buttons}
        hasScroll
      >
        <Spin
          ecId={`${(this && this.props && this.props.ecId) || ''}_Spin@x38tr5`}
          spinning={editLoading}
        >
          {editStep === 1 && this.getForm(accountForm, fields)}
          {editStep === 2 &&
            (mailType == 3
              ? ExchangeResult(validateLoading, editResult)
              : ResultPage(validateLoading, editResult, mailType))}
        </Spin>
        <RenderChooseFolder
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_RenderChooseFolder@arsau3`}
          visible={this.state.autoGetFolderVisible}
          onCancel={this.onCancelAutoGetFolder}
          value={this.state.chooseFolderName}
          options={this.state.chooseFolders}
          onChangeFolderName={this.onChangeFolderName}
          onSubmit={this.onSetFolderName}
        />
      </WeaDialog>
    );
  }
}

export default Edit;
